package com.markerhub.controller;

import cn.hutool.core.map.MapUtil;
import lombok.extern.slf4j.Slf4j;

import com.google.code.kaptcha.Producer;
import com.markerhub.common.lang.Const;
import com.markerhub.common.lang.Result;
import com.markerhub.entity.SysUser;
import com.markerhub.security.LoginFailureHandler;
import com.markerhub.security.LoginSuccessHandler;
import com.markerhub.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
public class AuthController extends BaseController {

    @Autowired
    Producer producer;

    @GetMapping("/captcha")
    public Result captcha() throws Exception {
        String key = UUID.randomUUID().toString();
        String code = producer.createText();
        
        log.info("生成验证码,key:{},code:{}",key,code);

        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image,"jpg",outputStream);

        BASE64Encoder encoder = new BASE64Encoder();
        String base64Img = encoder.encode(outputStream.toByteArray());

        redisUtil.set(Const.CAPTCHA_KEY+key,code,120);

        return Result.succ(MapUtil.builder().put("token",key)
                                            .put("captchaImg","data:image/jpeg;base64," + base64Img)
                                            .build());
    }
    
    /**
	 * 获取用户信息接口
	 * @param authentication
	 * @return
	 */
	@GetMapping("/sys/userInfo")
	public Result userInfo(Authentication authentication) {

		SysUser sysUser = (SysUser)authentication.getPrincipal();

		return Result.succ(MapUtil.builder()
				.put("id", sysUser.getId())
				.put("username", sysUser.getUsername())
				.put("avatar", sysUser.getAvatar())
				.put("created", sysUser.getCreated())
				.map()
		);
	}
}
